package com.chenva;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.util.List;

/**
 * 描述: 增加了一段描述
 *
 * @author zhaojk
 * @since v1.0
 */
public class TestDemo {
    public static void main1111(String[] args) {
        File file = new File("C:\\Users\\25673\\Desktop\\a.txt");
        List<String> lines = FileUtil.readUtf8Lines(file);
        for (String line : lines) {
            if (line.startsWith("https")) {
                String mainName = FileUtil.mainName(line);
                System.out.println(mainName);
                HttpUtil.downloadFile(line, new File("temp/" + mainName + ".ts"));
            }
        }
        System.out.println("Done !");
    }


    public static void main(String[] args) {
        boolean b = mergeFiles(new File("C:\\IdeaProjects\\testapp\\temp").listFiles(), "test.ts");
        System.out.println(b);
    }

    public static boolean mergeFiles(File[] fpaths, String resultPath) {
        if (fpaths == null || fpaths.length < 1) {
            return false;
        }

        if (fpaths.length == 1) {
            return fpaths[0].renameTo(new File(resultPath));
        }
        for (File fpath : fpaths) {
            if (!fpath.exists() || !fpath.isFile()) {
                return false;
            }
        }
        File resultFile = new File(resultPath);

        try {
            FileOutputStream fs = new FileOutputStream(resultFile, true);
            FileChannel resultFileChannel = fs.getChannel();
            FileInputStream tfs;
            for (File fpath : fpaths) {
                tfs = new FileInputStream(fpath);
                FileChannel blk = tfs.getChannel();
                resultFileChannel.transferFrom(blk, resultFileChannel.size(), blk.size());
                tfs.close();
                blk.close();
            }
            fs.close();
            resultFileChannel.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        // for (int i = 0; i < fpaths.length; i ++) {
        // fpaths[i].delete();
        // }

        return true;
    }


}
